package com.goldcn.order.service;

import com.goldcn.common.DataUtils;
import com.goldcn.common.HttpUtil;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.config.ProConstants;
import com.goldcn.order.dao.OrderInfoMapper;
import com.goldcn.order.dao.OrderItemMapper;
import com.goldcn.order.dto.*;
import com.goldcn.order.model.OrderInfo;
import com.goldcn.order.model.OrderItem;
import com.google.common.base.Objects;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 1111 on 2016/11/30.
 */
@Service
public class OrderIndexService {

    private Logger logger = Logger.getLogger(OrderService.class);
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    public boolean addIndex(List<Long> orderIDList, String mobile) {
        try {
            for (Long orderID : orderIDList) {
                OrderIndexDto indexDto = new OrderIndexDto();
                OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
                indexDto.setOrderID(orderID.toString());
                indexDto.setOrderNO(orderInfo.getOrderNO());
                indexDto.setAddress(orderInfo.getAddressID());
                indexDto.setAddTime(orderInfo.getAddTime().toString());
                indexDto.setBranchID(orderInfo.getBranchID() == null ? null : orderInfo.getBranchID().toString());
                indexDto.setBuyersID(orderInfo.getUserID().toString());
                indexDto.setBuyersName(orderInfo.getUserName());  //买家名字
                UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(orderInfo.getUserID());
                mobile = userInfoForOrderDto.getMobile();
                indexDto.setMobile(mobile);  //买家电话
                indexDto.setSalesID(orderInfo.getSalesID() == null ? null : orderInfo.getSalesID().toString());
                indexDto.setSalesManagerID(orderInfo.getSalesManagerID() == null ? null : orderInfo.getSalesManagerID().toString());
                indexDto.setStatus(orderInfo.getState());
                indexDto.setSubbranchID(orderInfo.getSubbranchID() == null ? null : orderInfo.getSubbranchID().toString());
                indexDto.setSupplierID(orderInfo.getSellerID() == null ? "0" : orderInfo.getSellerID().toString());
                indexDto.setSupplierName(orderInfo.getSellerName());
                indexDto.setTwoLevelBranchID(orderInfo.getTwoLevelBranchID() == null ? null : orderInfo.getTwoLevelBranchID().toString());
                indexDto.setAmount(orderInfo.getAmount());
                indexDto.setQty(orderInfo.getqty());
                indexDto.setCouponType(orderInfo.getCouponType());
                indexDto.setPointQty(orderInfo.getPointQty());
                indexDto.setPointAmount(orderInfo.getPointAmount());
                indexDto.setOrderPayType(orderInfo.getOrderPayType() == null ? "0" : orderInfo.getOrderPayType() + "");
                indexDto.setCompanyID(orderInfo.getCompanyID() + "");
                //订单中新添加的索引字段
                indexDto.setSureTime(orderInfo.getSureTime() == null ? "0" : orderInfo.getSureTime() + "");
                indexDto.setSendTime(orderInfo.getSendTime() == null ? "0" : orderInfo.getSendTime() + "");
                indexDto.setFinishTime(orderInfo.getFinishTime() == null ? "0" : orderInfo.getFinishTime() + "");
                indexDto.setPayTime(orderInfo.getPayTime() == null ? "0" : orderInfo.getPayTime() + "");
                indexDto.setPayType(orderInfo.getPayType() == null ? 0 : orderInfo.getPayType());
                indexDto.setPayNO(orderInfo.getPayNo() == null ? "" : orderInfo.getPayNo());
                indexDto.setInvoicesType(orderInfo.getInvoicesType() == null ? 0 : orderInfo.getInvoicesType());
                indexDto.setOrderType(orderInfo.getOrderType() == null ? "1" : orderInfo.getOrderType() + "");
                List<OrderItemIndexDto> itemIndexDtoList = new ArrayList<>();
                List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderID);
                for (OrderItem item : itemList) {
                    OrderItemIndexDto itemIndexDto = new OrderItemIndexDto();
                    itemIndexDto.setGoodsID(item.getGoodsID().toString());
                    itemIndexDto.setGoodsImg(item.getGoodsImg());
                    itemIndexDto.setGoodsName(item.getGoodsName());
                    itemIndexDto.setGoodsSku(item.getGoodsSku());
                    itemIndexDto.setItemID(item.getItemID().toString());
                    itemIndexDto.setPrice(item.getPrice());
                    itemIndexDto.setRetailPrice(item.getRetailPrice());
                    itemIndexDto.setQty(item.getQty());
                    itemIndexDtoList.add(itemIndexDto);
                }
                indexDto.setOrderItem(itemIndexDtoList);

                indexDto.setType(orderInfo.getType());

                //线下订单添加核销失效时间
                indexDto.setCheckInvalidTime(orderInfo.getCheckInvalidTime() == null ? "0" : orderInfo.getCheckInvalidTime() + "");
                indexDto.setCancelTime(orderInfo.getCancelTime() == null ? "0" : orderInfo.getCancelTime() + "");
                indexDto.setCheckCode(orderInfo.getCheckCode() == null ? "" : orderInfo.getCheckCode());
                Map<String, Object> traceabilityObject = getTraceabilityObject(orderInfo.getUserID(),orderInfo.getSalesManagerID(),orderInfo);
                if (traceabilityObject != null) {
                    indexDto.setOpathName(traceabilityObject.get("opathName") == null ? "" : traceabilityObject.get("opathName") + "");
                } else {
                    indexDto.setOpathName("");
                }
                DataResult result = HttpUtil.httpPost(ProConstants.ESURL + "/order/newIndex", indexDto, restTemplate);
                if (result.getIsSuccess() != 1) {
                    logger.error(orderID + "-----------error");
                    throw new ServiceException("新建索引失败", RestConst.ErrorCode.SERVICE_FAIL);
                }
            }
        } catch (Exception e) {
            throw new ServiceException("新建索引失败", e);
        }
        return true;
    }

    public boolean addPayNoIndex(List<Long> orderIDList) {
        try {
            for (Long orderID : orderIDList) {
                OrderIndexStateDto indexDto = new OrderIndexStateDto();

                OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
                indexDto.setOrderID(orderInfo.getOrderID().toString());
                indexDto.setSureTime(orderInfo.getSureTime() == null ? "0" : orderInfo.getSureTime() + "");
                indexDto.setSendTime(orderInfo.getSendTime() == null ? "0" : orderInfo.getSendTime() + "");
                indexDto.setFinishTime(orderInfo.getFinishTime() == null ? "0" : orderInfo.getFinishTime() + "");
                indexDto.setPayTime(orderInfo.getPayTime() == null ? "0" : orderInfo.getPayTime() + "");
                indexDto.setPayType(orderInfo.getPayType() == null ? 0 : orderInfo.getPayType());
                indexDto.setPayNO(orderInfo.getPayNo() == null ? "" : orderInfo.getPayNo());

                DataResult result = HttpUtil.httpPost(ProConstants.ESURL + "/order/index", indexDto, restTemplate);
                if (result.getIsSuccess() != 1) {
                    logger.error(orderID + "-----------error");
                    throw new ServiceException("更新索引失败", RestConst.ErrorCode.SERVICE_FAIL);
                }
            }
        } catch (Exception e) {
            throw new ServiceException("更新索引失败", e);
        }
        return true;
    }

    //获取下订单需要的UserInfo及其组织信息
    private Object getUserInfoForOrder(Long userID) {
        JSONObject jsonObject = HttpUtil.httpGetJSONObject(ProConstants.getUserInfoForOrder + userID, restTemplate);
        //if (jsonObject.get("isSuccess") != 1) {
        if (!com.google.common.base.Objects.equal(DataUtils.getInteger(jsonObject, "isSuccess"), 1)) {
            System.out.println(userID);
            throw new ServiceException("调用base服务获取用户信息接口出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return (UserInfoForOrderDto) JSONObject.toBean(jsonObject.getJSONObject("data"), UserInfoForOrderDto.class);
    }

    private Map<String, Object> getTraceabilityObject(Long userID,Long salesManagerID,OrderInfo orderInfo) {
        Long deptID = 0L;
        if(!Objects.equal(orderInfo.getSubbranchID(),0L)){
            deptID = orderInfo.getSubbranchID();
        }else if(!Objects.equal(orderInfo.getTwoLevelBranchID(),0L)){
            deptID = orderInfo.getTwoLevelBranchID();
        }else if(!Objects.equal(orderInfo.getBranchID(),0L)){
            deptID = orderInfo.getBranchID();
        }
        String exSql = userID+"/"+(salesManagerID == null ? 0L : salesManagerID)+"/"+deptID;
        DataResult result = HttpUtil.httpGet(ProConstants.getTraceability + exSql, restTemplate);
        if (result.getIsSuccess() == 1) {
            return (Map<String, Object>) result.getData();
        } else {
            System.out.print("-----调用base服务查询用户溯源信息失败-----");
        }
        return null;
    }

    public boolean deleteIndex(Long orderID) {
        try {
            DataResult result = HttpUtil.httpPost(ProConstants.ESURL + "/order/delIndex/" + orderID, null, restTemplate);
            if (result.getIsSuccess() != 1) {
                throw new ServiceException("删除索引失败", RestConst.ErrorCode.SERVICE_FAIL);
            }
        } catch (Exception e) {
            throw new ServiceException("删除索引失败", e);
        }
        return true;
    }

    public boolean updateState(OrderIndexStateDto stateDto) {
        try {
            DataResult result = restTemplate.postForObject(ProConstants.ESURL + "/order/index",stateDto,DataResult.class);
            if (result.getIsSuccess() != 1) {
                throw new ServiceException("修改索引失败", RestConst.ErrorCode.SERVICE_FAIL);
            }
        } catch (Exception e) {
            throw new ServiceException("修改索引失败", e);
        }
        return true;
    }


    public boolean updateOffline(OrderIndexOfflineDto indexOfflineDto) {
        try {
            DataResult result = HttpUtil.httpPost(ProConstants.ESURL + "/order/index", indexOfflineDto, restTemplate);
            if (result.getIsSuccess() != 1) {
                throw new ServiceException("修改索引失败", RestConst.ErrorCode.SERVICE_FAIL);
            }
        } catch (Exception e) {
            throw new ServiceException("修改索引失败", e);
        }
        return true;
    }


    public boolean updateIndexTest(List<Long> orderIDList) {
        try {
            for (Long orderID : orderIDList) {
                OrderIndexTypeDto indexDto = new OrderIndexTypeDto();

                OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
                List<OrderItem> orderItems = orderItemMapper.selectByOrderID(orderID);
                indexDto.setOrderID(orderInfo.getOrderID().toString());
                indexDto.setOrderPayType(orderInfo.getOrderPayType() == null ? "0" : orderInfo.getOrderPayType() + "");
                indexDto.setPayNO(orderInfo.getPayNo() == null ? "" : orderInfo.getPayNo());
                indexDto.setAmount(orderInfo.getAmount());
                indexDto.setOrderItem(orderItems);
                DataResult result = HttpUtil.httpPost(ProConstants.ESURL + "/order/index", indexDto, restTemplate);
                if (result.getIsSuccess() != 1) {
                    logger.error(orderID + "---更新索引失败-----------error");
                }
            }
        } catch (Exception e) {
            throw new ServiceException("更新索引失败", e);
        }
        return true;
    }

    public boolean updateIndexCompanyID(List<Long> orderIDList) {
        try {
            for (Long orderID : orderIDList) {
                JSONObject data = new JSONObject();

                OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
                data.put("orderID", orderInfo.getOrderID() + "");
                data.put("companyID", orderInfo.getCompanyID() + "");
                DataResult result = HttpUtil.httpPost(ProConstants.ESURL + "/order/index", data, restTemplate);
                if (result.getIsSuccess() != 1) {
                    logger.error(orderID + "---更新索引失败-----------error");
                }
            }
        } catch (Exception e) {
            throw new ServiceException("更新索引失败", e);
        }
        return true;
    }



}



